package com.xunxi.mimi.ui.base;

import android.util.SparseArray;
import android.view.View;

import androidx.recyclerview.widget.RecyclerView;

/**
 * 功能描述
 * Created by hxy on 2016/6/28.
 */
public class RecycleViewHolder extends RecyclerView.ViewHolder {
    //所有的子控件
    private SparseArray<View> mViews;
    //itemview
    private View mConvertView;
    private BaseRecycleAdapter adapter;

    //初始化的设置
    protected RecycleViewHolder(View itemView) {
        super(itemView);
        this.mViews = new SparseArray<>();
        mConvertView = itemView;
    }

    public <T> RecycleViewHolder(View itemView, final BaseRecycleAdapter<T> adapter) {
        super(itemView);
        this.mViews = new SparseArray<>();
        mConvertView = itemView;
        if (adapter.getItemClickListener() != null) {
            itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    adapter.getItemClickListener().onItemClickListener(v,getAdapterPosition() - adapter.getHeaderViewsCount());
                }
            });
        }
        if (adapter.getItemLongClickListener() != null){
            itemView.setOnLongClickListener(new View.OnLongClickListener() {
                @Override
                public boolean onLongClick(View view) {
                    adapter.getItemLongClickListener().onItemLongClickListener(RecycleViewHolder.this,
                            getAdapterPosition() - adapter.getHeaderViewsCount());
                    return false;
                }
            });
        }
        this.adapter = adapter;
    }


    public View getConvertView() {
        return mConvertView;
    }

    /**
     * 通过控件的Id获取对于的控件，如果没有则加入views
     *
     * @param viewId 组件id
     * @return 当前组件
     */
    public <T extends View> T getView(int viewId) {
        View view = mViews.get(viewId);
        if (view == null) {
            view = mConvertView.findViewById(viewId);
            mViews.put(viewId, view);
        }
        try {
            return (T) view;
        } catch (ClassCastException e) {
            e.printStackTrace();
        }
        return null;
    }
}
